package com.ice.app.system.dict.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.ice.app.system.constants.CommonConstant;
import com.ice.app.system.dict.vo.DictVo;
import com.ice.app.system.entity.Dict;
import com.ice.app.system.mapper.DictMapper;
import com.iceframework.core.utils.KeyUtils;
import com.iceframework.core.utils.WebUtils;

/**
 * 
 * 业务逻辑层： 数据字典表
 * 
 * @author Mr.Palo
 * @email 442803840@qq.com
 * 
 */
@Service
public class DictService {

	@Autowired
	private DictMapper dictMapper;

	@Autowired
	private DictDataService dictDataService;

	// ----------------------------------------自动生成--------------------------------------------

	/**
	 * 字典保存
	 * 
	 * @param dict
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean saveDict(Dict dict) throws Exception {
		if (StringUtil.isNotEmpty(dict.getId())) {
			// 修改操作
			Dict old = this.getDict(dict.getId());
			dict.setUpdateBy(WebUtils.getUserName());
			dict.setUpdateDate(new Date());
			if (old != null) {
				return dictMapper.updateByPrimaryKeySelective(dict) > 0;
			}
			return false;
		} else {
			// 保存操作
			String key = KeyUtils.genKey("Dict");
			dict.setId(key);
			dict.setStatus(CommonConstant.SYS_STATUS_VALID);
			dict.setCreateBy(WebUtils.getUserName());
			dict.setCreateDate(new Date());
			dict.setUpdateBy(WebUtils.getUserName());
			dict.setUpdateDate(new Date());
			return dictMapper.insertSelective(dict) > 0;

		}
	}

	/**
	 * 根据主键删除字典
	 * 
	 * @param key
	 * @return
	 */
	@Transactional
	public boolean deleteDict(String key) {
		return dictMapper.deleteByPrimaryKey(key) > 0;
	}

	/**
	 * 根据多个主键删除字典
	 * 
	 * @param keys
	 * @return
	 */
	@Transactional
	public boolean deleteDicts(String keys) {
		if (!StringUtils.isEmpty(keys)) {
			String[] strs = keys.split(",");
			for (String key : strs) {
				this.deleteDict(key);
			}
			return true;
		}
		return false;
	}

	/**
	 * 根据主键获取字典实体
	 * 
	 * @param key
	 * @return
	 */
	public Dict getDict(String key) {
		return dictMapper.selectByPrimaryKey(key);
	}

	/**
	 * 根据给定条件获取字典实体集合
	 * 
	 * @param key
	 * @return
	 */
	public List<Dict> getDicts(Dict dict) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dict", dict);
		return dictMapper.selectByFilter(map);
	}

	// ----------------------------------------自定义（Public）---------------------------------------------

	/**
	 * 根据字典Code查询数据字典项
	 * 
	 * @param dictCode
	 * @return
	 */
	public List<DictVo> getDictVoByDictCode(String dictCode) {
		return dictDataService.getDictVoByCode(dictCode);
	}
}